<template>
		
		<view class="contract-item-content">
			<!-- 这里设置了z-paging加载时禁止自动调用reload方法，自行控制何时reload（懒加载）-->
			<!--  :enable-back-to-top="currentIndex===tabIndex" 在微信小程序上可以多加这一句，因为默认是允许点击返回顶部的，但是这个页面有多个scroll-view，会全部返回顶部，所以需要控制是当前index才允许点击返回顶部 -->
			<z-paging ref="paging" v-model="dataList" @query="queryList" :fixed="false" :auto="true" :show-default-loading-more-text="false"	>
				<!-- 如果希望其他view跟着页面滚动，可以放在z-paging标签内 -->
				<template #top>
					<view class="" slot="top" >
						<fui-nav-bar title="管理商品" isFixed isOccupy background="#fff" @leftClick="pageBack">
							<template #right>
								<view class="u-font-28 u-p-r-35" slot="right" v-if="!isCheckShow" @tap="clearModal = true;">
									一键清空
								</view>
							</template>
						</fui-nav-bar>
						<view class="shop-header">
							<image src="/static/logo.png" mode="" class="shop-logo"></image>
							<view class="shop-name u-text-center">
								{{ownerName}}
							</view>
							<view class=" u-m-t-20 u-m-b-30 u-text-center">
								已签约 {{itemsCount}} 个单品
							</view>
							<view class="u-p-20">
								<fui-search-bar  searchText v-model="searchValue" placeholder="商品名称" :cancel="false"  background="#fff" inputBackground="#f0f0f0" @input="reloadFn" paddingTb="0" paddingLr="0" radius="45"></fui-search-bar>
								<!-- <u-search :searchIconFlag="true" v-model="searchValue" input-align="center" placeholder="商品名称" height="70" :border-color="'#FFBB1A'" :bg-color="'#fff'" 	:show-action="false" @change="reloadFn" @search="reloadFn"></u-search> -->
							</view>
						</view>
						
					</view>
				</template>
				<view class="history-container u-p-l-35 u-p-r-35">
					<view class="" v-for="(item, index) in dataList" :key="item.id" >
						<view class="history-item u-p-t-30 u-p-b-30  u-flex ">
							<view class="iconfont icon-jianshao" style="margin-right: 20rpx;color: #FF551A;" @click="delItemBtnClick(item.id)" v-if="!isCheckShow" ></view>
							<image :src="item.url" mode="" style="display:block;width: 100rpx;height: 100rpx;margin-right: 20rpx;border-radius: 10rpx;"></image>
							<view class="" style="flex: 1;overflow: hidden;">
								<view class="u-font-30 u-line-1" style="font-weight: 500;">{{item.itemName}}</view>
								<view class="u-font-24 u-m-t-10" v-if="item.specification" style=" display: inline-block; color: #999;background-color: #f8f8f8;padding: 10rpx 12rpx;border-radius: 10rpx;">
									{{item.specification}}
								</view>
							</view>
							<view class="" style="width: 200rpx;">
								<view class="u-text-right" style="color:#999 ;" v-if="item.isInheritFromBrandOwner">
									{{item.brandOwnerName}}
								</view>
								<view class="u-text-right" >
									<view class=" u-font-32" style="color: #ff551a;" v-if="isCheckShow">
										￥{{item.price}}
									</view>
									<view  v-if="!isCheckShow">
										<view class="u-font-32" style="color: #ff551a;" v-if="item.isInheritFromBrandOwner">
											￥{{item.price}}
										</view>
										<view class="u-flex u-row-right" style="color: #333;" v-if="!item.isInheritFromBrandOwner">
											￥<input type="number" v-model="item.price" name="" id="" style="border: 1px solid #999;border-radius: 10rpx; text-align: center;width: 150rpx;height: 50rpx;">
										</view>
									</view>
									
								</view>
							</view>
						</view>
					</view>
				</view>
				<template #bottom>
					<view>
						<view class="u-flex bottom-menu-container" v-if="isCheckShow" >
							<view class="u-flex u-p-40 bottom-menu" @click="createTemplate=true" >
								<image src="/static/xiaoshou/tiqumoban.png" mode="" style="width: 48rpx;height: 48rpx;"></image>
								<view class="u-m-t-20 u-font-24" style="font-weight: bold;">提取模板</view>
							</view>
							<view class="u-flex u-p-40 bottom-menu" style="border-right: none;" @click="chooseTemplate= true">
								<image src="/static/xiaoshou/laizimoban.png" mode="" style="width: 48rpx;height: 48rpx;" ></image>
								<view class="u-m-t-20 u-font-24" style="font-weight: bold;">来自模板</view>
							</view>
							<view class="u-flex u-p-40 bottom-menu" style="border-right: none;" @click="itemMangeFn">
								<image src="/static/xiaoshou/guanlishangpin.png" mode="" style="width: 48rpx;height: 48rpx;"></image>
								<view class="u-m-t-20 u-font-24" style="font-weight: bold;">管理商品</view>
							</view>
							<view class="u-flex u-p-40 bottom-menu" >
								<image src="/static/xiaoshou/tianjiashangpin.png" mode="" @click="$mRouter.push({ route: '/pages/sale/saleContract/addItem?salesAgreementId='+salesAgreementId+'&ownerName='+ownerName })" style="width: 48rpx;height: 48rpx;"></image>
								<view class="u-m-t-20 u-font-24" style="font-weight: bold;">添加商品</view>
							</view>
						</view>
						<view v-else>
							<!-- bottom的内容 -->
							<view class="history-bottom u-p-r-35 u-p-l-35 u-flex u-col-center u-row-between">
								<button type="default" class="history-del_btn" style="border: 1px solid #333; background-color: #fff;" @click="isCheckShow = true">取消</button>
								<button type="default" class="history-del_btn" @click="updateItemPrice">保存</button>
							</view>
						</view>
					</view>
				</template>
			
			</z-paging>
			<fui-modal :show="delModel" :descr="'您确定要从合约中移除此商品？'"  @cancel="delModel=false" @click="delContractItem" ></fui-modal>
			<fui-modal :show="clearModal" :descr="'您确定要此合约的商品清空吗？'" @cancel="clearModal=false" @click="clearAgreementItemFn" ></fui-modal>
			<fui-modal :show="createTemplate"  @click="createTemplateFn" title="提取为价格模板"  @cancel="createTemplate=false" >
				<view class="u-p-35 " >
					<fui-input v-model="templateName" placeholder="请输入要生成的模板名称" type="text" />
				</view>
			</fui-modal>
			<fui-modal :show="chooseTemplate"  @click="exportTemplateFn" title="从模板中导入价格" @cancel="chooseTemplate=false">
				<view class="u-p-35 " style="width: 100%;">
					<view  class=" u-p-t-30 u-p-b-30 u-font-32  u-flex u-col-center" style="background-color: #fff;">
						<view class="">
							模板
						</view>
						<view class="u-flex u-col-center u-row-between"  style="flex:1;" @click="templateShow = true">
							<view class="u-m-l-30"  :style="{'flex':1,'color':chooseTemplateName==='请选择价格模板'?'rgb(192, 196, 204)':'#333'}">
								{{chooseTemplateName}}
							</view>
							<fui-icon name="arrow-right"></fui-icon>
						</view>
						
					</view>
					<view  class=" u-p-t-30 u-p-b-30 u-font-32  u-flex u-col-center" style="background-color: #fff;">
						<view class="u-m-r-20">
							方式
						</view>
						<view class="u-flex u-col-center u-row-between"  style="flex:1;" >
							<fui-radio-group name="radio" v-model="exportMethod"  style="width: 100%;">
								<view class="u-flex">
									<fui-label>
										<view class="fui-align__center">
											<fui-radio value="1"  checked></fui-radio>
											<text class=" u-m-l-6">新增</text>
										</view>
									</fui-label>
									<fui-label :margin="['0','0','0','40rpx']">
										<view class="fui-align__center">
											<fui-radio value="2"></fui-radio>
											<text class="">覆盖</text>
										</view>
									</fui-label>
									<fui-label :margin="['0','0','0','40rpx']">
										<view class="fui-align__center">
											<fui-radio value="3"></fui-radio>
											<text class="">新增且覆盖</text>
										</view>
									</fui-label>
								</view>
							</fui-radio-group>
							<!-- <u-radio-group v-model="exportMethod" active-color='#ffbb1a'>
								<u-radio :name="1" >新增</u-radio>
								<u-radio :name="2" >覆盖</u-radio>
								<u-radio :name="3" >新增且覆盖</u-radio>
							</u-radio-group> -->
						</view>
						
					</view>
				</view>
			</fui-modal>
			
			<fui-bottom-popup :show="templateShow"  safe-area-inset-bottom	@close="templateShow = false;">
				<view style="min-height: 800rpx;">
					<view class="u-text-center  u-font-32" style="line-height: 100rpx;height: 100rpx;font-weight: bold;">
						选择价格模板
					</view>
					<TemplateList :chooseId="chooseTemplateId" @sendValue="sendValue"></TemplateList>
					<!-- <view class="" style="width: 80%;background-color: #ffbb1a;margin:20rpx auto;height: 80rpx;text-align: center; line-height: 80rpx; border-radius: 50rpx;">
						确定
					</view> -->
				</view>
			</fui-bottom-popup>
		</view>
	
</template>

<script>
	import TemplateList from './compontents/TemplateList.vue'
	export default {
		data() {
			return {
				//v-model绑定的这个变量不要在分页请求结束中自己赋值！！！
				dataList: [],
				clearModal:false,
				isCheckShow:true,
				templateShow:false,
				allSelect:false,
				createTemplate:false,
				delModel:false,
				delItemId:'',
				itemsCount:0,
				ownerName:'',
				salesAgreementId:'',
				ownerId:"",
				searchValue:'',
				templateName:'',
				chooseTemplate:false,
				chooseTemplateId:'',
				chooseTemplateName:'请选择价格模板',
				exportMethod:1,
				refreshIfNeeded:false,
			}
		},
		onLoad(options) {
			this.ownerName = options.ownerName;
			this.ownerId = options.ownerId;
			// this.shopId = options.shopId;
			this.salesAgreementId = options.salesAgreementId;
		},
		onShow() {
			uni.$off('sendContract')//建议先销毁一次监听，再进行新的一次监听，否则会出现重复监听的现象
			let that = this;
			uni.$once('sendContract',function(data){
				that.reloadFn();
			})
			var pages = getCurrentPages(); // 获取当前页面栈
			var currentPage = pages[pages.length - 1]; // 当前页面
			if (currentPage._data.refreshIfNeeded) {
				currentPage._data.refreshIfNeeded = false;
				//这里为要调用的函数，重新获取数据，记得加上this
				// this.itemListInit();
			}
		},
		components:{
			TemplateList
		},
		
		methods: {
			async clearAgreementItemFn(data){
				if(data.index === 0){
					this.clearModal = false;
					return;
				};
				this.clearModal = false;
				uni.showLoading({
					title:'loading...'
				})
				const res = await this.$newHttp.delete('api/Shop/v2/ClearSalesAgreementItems?salesAgreementId='+this.salesAgreementId);
				uni.hideLoading()
				if(res.code === 200){
					uni.showToast({
						title:'清除成功'
					});
					this.isCheckShow = true;
					this.$refs.paging.reload();
				}else{
					uni.$fui.toast(res.erroMessage)
				}
			},
			sendValue(val){
				this.chooseTemplateId = val.id;
				this.chooseTemplateName= val.name;
				this.templateShow = false;
			},
			// 从价格模板中导入价格
			async exportTemplateFn(data){
				if(data.index === 0){
					this.chooseTemplate = false;
					return;
				};
				
				uni.showLoading({
					title:"loading..."
				})
				if(this.chooseTemplateId === ''){
					uni.hideLoading();
					uni.$fui.toast('价格模板不得为空');
					return false;
				};
				let params = {
					salesAgreementId:this.salesAgreementId,
					templateId:this.chooseTemplateId,
					copyPolicy:this.exportMethod
				}
				const res =  await this.$newHttp.put('api/Shop/v2/UpdateSalesAgreementItemsByTemplate',params);
				uni.hideLoading();
				if(res.code === 200){
					uni.showToast({
						title:'导入成功',
					})
					this.templateName = '';
					this.chooseTemplateId = '';
					this.chooseTemplateName= '';
					this.exportMethod = 1;
					this.chooseTemplate = false;
					this.$refs.paging.reload();
				}else{
					uni.$fui.toast('导入失败');
				}
			},
			// 提取合约商品为 价格模板
			async createTemplateFn(data){
				if(data.index === 0){
					this.createTemplate = false;
					return;
				};
				uni.showLoading({
					title:"loading..."
				})
				if(this.templateName === ''){
					uni.hideLoading();
					uni.$fui.toast('模板名称不得为空');
					return false;
				};
				let params = {
					id:this.salesAgreementId,
					name:this.templateName
				}
				const res =  await this.$newHttp.post('api/Shop/v2/ExtractAsPriceTemplate',params);
				uni.hideLoading();
				if(res.code === 200){
					uni.showToast({
						title:'生成新模板成功',
					})
					this.templateName = '';
					this.createTemplate = false;
					this.$refs.paging.reload();
				}else{
					uni.$fui.toast('生成新模板失败');
				}
			},
			// 删除商品icon 点击时发生
			delItemBtnClick(id){
				this.delModel = true;
				this.delItemId = id;
			},
			// 确认删除商品
			async delContractItem(data){
				if(data.index === 0){
					this.delModel = false;
					return;
				};
				const res = await this.$newHttp.delete('api/Shop/v2/RemoveSalesAgreementItems?salesAgreementId='+this.salesAgreementId+'&saItemId='+this.delItemId);
				if(res.code === 200){
					let index = this.dataList.findIndex(item=>{
						return item.id === this.delItemId
					});
					this.dataList.splice(index,1);
				}else{
					uni.$fui.toast('删除商品失败')
				}
			},
			// 点击管理商品
			itemMangeFn(){
				this.isCheckShow = false;
			},
			reloadFn(){
				this.$refs.paging.reload();
			},
			// 全选
			checkedAll(e) {
				this.dataList.map(val => {
					val.checked = e.value;
				});
			},
			async updateItemPrice(){
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				let ary = [];
				this.dataList.forEach(item=>{
					// if(!item.isInheritFromBrandOwner){
					// 	ary.push({
					// 		id:item.id,
					// 		itemId:item.itemId,
					// 		price:item.price
					// 	});
					// }
					ary.push({
						id:item.id,
						itemId:item.itemId,
						price:item.price
					});
				});
				console.log(ary);
				if(ary.length == 0){
					uni.hideLoading({});
					uni.$fui.toast('没有能修改的价格');
					// return false;
				};
				let allNoZero = ary.every(item=>{return item.price!==''&&item.price>0});
				if(!allNoZero){
					uni.hideLoading({});
					uni.$fui.toast('商品价格不得有空项，或者小于0');
					return false;
				}
				let params = {
					items:ary,
					salesAgreementId:this.salesAgreementId
				}
				const res = await this.$newHttp.put('api/Shop/v2/UpdateSalesAgreementByManual',params);
				uni.hideLoading({});
				if(res.code == 200){
					this.isCheckShow = true;
					this.$refs.paging.reload();
				}else{
					uni.$fui.toast('保存失败，错误信息：'+res.erroMessage);
				}
				
			},
			async queryList(pageNo, pageSize) {
				//组件加载时会自动触发此方法，因此默认页面加载时会自动触发，无需手动调用
				//这里的pageNo和pageSize会自动计算好，直接传给服务器即可
				//模拟请求服务器获取分页数据，请替换成自己的网络请求
				const params = {
					pageIndex: pageNo,
					pageSize: pageSize,
					salesAgreementId:this.salesAgreementId
				}
					
				if(this.searchValue != ''){
					params.itemName = this.searchValue
				}
				uni.showLoading({
					title: 'loading...',
					mask: false
				});
				const res = await this.$newHttp.get('api/Shop/v2/GetSalesAgreementItems', { params: params } );
				uni.hideLoading({})
				if(res.code === 200){
					let ary = res.data.list.map(item=>{
						item.checked = this.allSelect;
						return item
					});
					this.$refs.paging.complete(ary);
					this.itemsCount = res.data.totalCount;
				}else{
					this.$refs.paging.complete(false);
				}
			},
		
		}
	}
</script>

<style lang="scss" scoped>
	@import '@/static/iconfont/iconfont.css'; 
	/* 注意:父节点需要固定高度，z-paging的height:100%才会生效 */
	.contract-item-content {
		height: 100%;
		.shop-header{
			background: #fff;
			overflow: hidden;
			// margin-bottom: 20rpx;
			.shop-logo{
				width: 120rpx;
				height: 120rpx;
				border-radius: 50%;
				margin: 48rpx auto 30rpx;
				display:block;
			}
			.shop-name{
				font-size: 32rpx;
				font-weight: 500;
				color: #333333;
			}
			
		}
		.bottom-menu-container{
			background-color: #fff;
			.bottom-menu{
				flex:1;border: 1px solid #eaeaee;flex-direction: column;align-items: center;justify-content: center;
			}
		}
	}
	.history-container{
		box-sizing: border-box;
		background-color: #fff;
		.history-item{
			width: 100%;
			background-color: #fff;
			// border-radius: 10rpx;
			border-bottom: 1px solid #eaeaea;
		}
		
	}
	.history-bottom{
		width: 100%;
		height: 138rpx;
		background-color: #fff;
		.history-del_btn{
			width: 44%;
			height: 80rpx;
			background: #FFBB1A;
			border-radius: 40rpx;
			font-size: 28rpx;
			line-height: 80rpx;
			text-align: center;
			margin: 0;
		}
	}
	
</style>
